package com.atomscat.lottery.service;

import com.atomscat.lottery.entity.db.LotteryActivityEntity;
import com.atomscat.lottery.entity.db.LotteryUserEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@RequiredArgsConstructor
public class ParticipateActivityService {
    private final LotteryUserService lotteryUserService;
    private final LotteryActivityService lotteryActivityService;
    private final LotteryActivityUserService lotteryActivityUserService;

    private static LotteryUserEntity getLotteryUserEntity(WxOAuth2UserInfo user, String appId) {
        LotteryUserEntity lotteryUserEntity = new LotteryUserEntity();
        lotteryUserEntity.setAppid(appId);
        lotteryUserEntity.setOpenid(user.getOpenid());
        lotteryUserEntity.setNickname(user.getNickname());
        lotteryUserEntity.setCity(user.getCity());
        lotteryUserEntity.setProvince(user.getProvince());
        lotteryUserEntity.setCountry(user.getCountry());
        lotteryUserEntity.setUnionid(user.getUnionId());
        lotteryUserEntity.setHeadimgurl(user.getHeadImgUrl());
        lotteryUserEntity.setSex(String.valueOf(user.getSex()));
        return lotteryUserEntity;
    }

    @Transactional
    public void participate(WxOAuth2UserInfo user, Long lotteryActivityId, String appId) {
        LotteryActivityEntity lotteryActivityEntity = lotteryActivityService.getLotteryActivityEntity(lotteryActivityId);
        if (lotteryActivityEntity == null) {
            throw new IllegalArgumentException("活动不存在");
        }
        if (!"recruiting".equals(lotteryActivityEntity.getStatus())) {
            throw new IllegalArgumentException("活动已停止报名");
        }
        LotteryUserEntity lotteryUserEntity = getLotteryUserEntity(user, appId);
        lotteryUserService.saveLotteryUser(lotteryUserEntity);
        if (lotteryActivityUserService.getLotteryActivityUser(lotteryActivityId, lotteryUserEntity.getId()) == null) {
            lotteryActivityUserService.createLotteryActivityUser(lotteryActivityId, lotteryUserEntity.getId());
        }
    }
}
